Declare @tmpDate datetime, @tmpDateNextMonth datetime
SET @tmpDate = '1-Nov-2013'
SET @tmpDateNextMonth = '1-Nov-2013'

WHILE @tmpDate <= '1-Jan-2014'
BEGIN
	
	Select @tmpDate

	DECLARE curUser CURSOR FOR 
	Select UserID from tblUser
	
	OPEN curUser

	Declare @UserID int, @TeamID int
	FETCH NEXT FROM curUser
	INTO @UserID

	WHILE @@FETCH_STATUS = 0
	BEGIN
		SET @tmpDateNextMonth = DateAdd(month,1, @tmpDate)
		Select top 1 @TeamID = TeamID from tblUser_Log
		Where UserID = @UserID
		And Convert(varchar(6), UpdateDate, 112) < Convert(varchar(6), @tmpDateNextMonth, 112)
		Order By UpdateDate DESC

		----Select top 1 * FROM tblUser_Log
		----Where UserID = @UserID
		----And Convert(varchar(6), UpdateDate, 112) < Convert(varchar(6), @tmpDate, 112)
		----Order By UpdateDate DESC

		IF @TeamID > 0
		BEGIN
			--Select @UserID UserID, @TeamID TeamID, @tmpDate
			Update CTI SET CTI.ClosedByTeamID = @TeamID  
			FROM tblCaseTaskIndex CTI
			INNER JOIN tblCaseProfileIndex CPI ON CTI.CaseRefID = CPI.CaseRefID And CTI.CaseSourceID = CPI.CaseSourceID
			Where Convert(varchar(6), CPI.ClosedOn, 112) = Convert(varchar(6), @tmpDate, 112)
			And CPI.ClosedBy = @UserID 

			Update CTI SET CTI.ProcessedByTeamID = @TeamID  
			FROM tblCaseTaskIndex CTI
			INNER JOIN tblCaseProfileIndex CPI ON CTI.CaseRefID = CPI.CaseRefID And CTI.CaseSourceID = CPI.CaseSourceID
			Where Convert(varchar(6), CPI.ClosedOn, 112) = Convert(varchar(6), @tmpDate, 112)
			And CPI.ProcessedBy = @UserID 
		END

		FETCH NEXT FROM curUser
		INTO @UserID
	END

	CLOSE curUser
	DEALLOCATE curUser

	SET @tmpDate = DateAdd(month,1, @tmpDate)
END
